import PubSub from "pubsub-js"

const app = getApp()
let setSong: SetSong, pauseSong: () => void, playSong: () => void

Component<DataModel, {}, MethodsModel>({
  properties: {
    offsetTab: {
      //表示是否需要对自定义tabbar的高度进行便宜
      type: Boolean,
      value: false,
    },
  },
  data: {
    songName: "",
    imgUrl: "",

    bottom: "-90rpx",
    opacity: 0,
    isPlay: false,
  },
  methods: {
    setSong(_, { songName, imgUrl }) {
      this.setData({ songName, imgUrl, isPlay: true })
    },
    pauseSong() {
      this.setData({ isPlay: false })
    },
    playSong() {
      this.setData({ isPlay: true })
    },
    changePlay() {
      if (this.data.songName === "未有歌曲在播放") return //如果没有歌名，则表示未播放过歌曲

      const bgm = wx.getBackgroundAudioManager()
      const { isPlay } = this.data
      if (isPlay) {
        PubSub.publish("pauseSong", false)
      } else {
        //当歌曲播放错误的时候，就会变成空串
        app.globalData.songUrl === "" ? PubSub.publish("changeSong",{type: "next"}) : bgm.play()
      }
      this.setData({ isPlay: !isPlay })
    },
    showPlayer({ target }) {
      if (target.id === "play" || this.data.songName === "未有歌曲在播放") return

      wx.navigateTo({
        url: "/pages/player/player",
      })
    },
  },

  //播放bar先不加旋转，因为多个页面的tabBar的独立实例，切换页面的时候大家的旋转角度不一样

  lifetimes: {
    created() {},
    attached() {
      const { songName, imgUrl } = app.globalData.song

      this.setData({
        songName,
        imgUrl,
        isPlay: app.globalData.isPlay,
        bottom: this.properties.offsetTab ? "90rpx" : "0",
        opacity: 1,
      })

      //要写成箭头函数，否则setSong中的this是undefined。并且要保存到外面，用于取消订阅
      setSong = (_, song) => this.setSong(_, song)
      PubSub.subscribe("setPlayBar", setSong)

      pauseSong = () => this.pauseSong()
      PubSub.subscribe("pauseSong", pauseSong)

      playSong = () => this.playSong()
      PubSub.subscribe("restartSong", playSong)
    },
    detached() {
      PubSub.unsubscribe(setSong)
      PubSub.unsubscribe(pauseSong)
      PubSub.unsubscribe(playSong)
    },
  },
})

interface DataModel {
  songName: string
  imgUrl: string

  bottom: string
  opacity: number

  isPlay: boolean

  offsetTab?: boolean
}

interface MethodsModel {
  setSong: SetSong
  pauseSong: () => void
  playSong: () => void
  changePlay: () => void
  showPlayer: (e: WechatMiniprogram.Touch) => void
  [key: string]: any
}

type Instance = WechatMiniprogram.Component.Instance<DataModel, {}, MethodsModel>

type SetSong = (this: Instance, msg: string, song: { songName: string; imgUrl: string }) => void
